package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import cn.beecloud.BCPay;
import cn.beecloud.BCQuery;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCBillOrder;
import cn.beecloud.entity.BCPayResult;
import cn.beecloud.entity.BCQueryBillResult;
import cn.beecloud.entity.BCReqParams;

/**
 * 支付测试
 */
public class ShoppingTestActivity extends BaseActivity implements View.OnClickListener {
    private Button bt_pay;
    private ProgressDialog mProgressDialog;
    private String toastMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping);
        bt_pay = ((Button) findViewById(R.id.bt_pay));
        bt_pay.setOnClickListener(this);
        mProgressDialog = new ProgressDialog(ShoppingTestActivity.this);
        mProgressDialog.setMessage("处理中，请稍候...");
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setCancelable(true);
    }

    @Override
    public void onClick(View v) {
        HashMap<String, String> mapOptional = new HashMap<>();
        mapOptional.put("ebOrderID", "0");
        mapOptional.put("userid", "6208");
        BCPay.getInstance(ShoppingTestActivity.this).reqAliPaymentAsync("忆年在线支付测试", 1,
                getCurrentTime(), mapOptional, callback);
    }

    private String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.CHINA);
        return simpleDateFormat.format(new Date());
    }

    BCCallback callback = new BCCallback() {
        @Override
        public void done(BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult) bcResult;
            String result = bcPayResult.getResult();
            Log.d("yuhao", "result=" + "支付失败, 原因: " + bcPayResult.getErrCode() +
                    " # " + bcPayResult.getErrMsg() +
                    " # " + bcPayResult.getDetailInfo());
            if (result.equals(BCPayResult.RESULT_SUCCESS)) {
                toastMsg = "用户支付成功";
            } else if (result.equals(BCPayResult.RESULT_CANCEL))
                toastMsg = "用户取消支付";
            else if (result.equals(BCPayResult.RESULT_FAIL)) {
                toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                        " # " + bcPayResult.getErrMsg() +
                        " # " + bcPayResult.getDetailInfo();
            }
            Message message = handler.obtainMessage();
            message.what = 1;
            handler.sendMessage(message);

            if (bcPayResult.getId() != null) {
                //你可以把这个id存到你的订单中，下次直接通过这个id查询订单
                Log.w(TAG, "bill id retrieved : " + bcPayResult.getId());
                //根据ID查询，此处只是演示如何通过id查询订单，并非支付必要部分
                getBillInfoByID(bcPayResult.getId());
            }
        }
    };

    void getBillInfoByID(String id) {

        BCQuery.getInstance().queryBillByIDAsync(id,
                new BCCallback() {
                    @Override
                    public void done(BCResult result) {
                        BCQueryBillResult billResult = (BCQueryBillResult) result;
                        Log.d("yuhao", "------ response info ------");
                        Log.d("yuhao", "------getResultCode------" + billResult.getResultCode());
                        Log.d("yuhao", "------getResultMsg------" + billResult.getResultMsg());
                        Log.d("yuhao", "------getErrDetail------" + billResult.getErrDetail());
                        if (billResult.getResultCode() != 0)
                            return;
                        Log.d("yuhao", "------- bill info ------");
                        BCBillOrder billOrder = billResult.getBill();
                        Log.d("yuhao", "订单唯一标识符：" + billOrder.getId());
                        Log.d("yuhao", "订单号:" + billOrder.getBillNum());
                        Log.d("yuhao", "订单金额, 单位为分:" + billOrder.getTotalFee());
                        Log.d("yuhao", "渠道类型:" + BCReqParams.BCChannelTypes.getTranslatedChannelName(billOrder.getChannel()));
                        Log.d("yuhao", "子渠道类型:" + BCReqParams.BCChannelTypes.getTranslatedChannelName(billOrder.getSubChannel()));
                        Log.d("yuhao", "订单是否成功:" + billOrder.getPayResult());

                        if (billOrder.getPayResult())
                            Log.d("yuhao", "渠道返回的交易号，未支付成功时，是不含该参数的:" + billOrder.getTradeNum());
                        else
                            Log.d("yuhao", "订单是否被撤销，该参数仅在线下产品（例如二维码和扫码支付）有效:"
                                    + billOrder.getRevertResult());

                        Log.d("yuhao", "订单创建时间:" + new Date(billOrder.getCreatedTime()));
                        Log.d("yuhao", "扩展参数:" + billOrder.getOptional());
                        Log.w("yuhao", "订单是否已经退款成功(用于后期查询): " + billOrder.getRefundResult());
                        Log.w("yuhao", "渠道返回的详细信息，按需处理: " + billOrder.getMessageDetail());

                    }
                });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    showToast(toastMsg);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清理当前的activity引用
        BCPay.clear();

        //使用微信的，在initWechatPay的activity结束时detach
        BCPay.detachWechat();

        //使用百度支付的，在activity结束时detach
        BCPay.detachBaiduPay();
    }
}
